package stardust.product.utils.transmit;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import stardust.core.log.Log;

public class TransmitListener extends Thread
{
  
  public static int TIMEOUT = 1000 * 60 * 60 * 12;
  
  private ServerSocket serverSocket;
  
  private int localPort;
  
  private String proxyHost;
  private int proxyPort;
  
  private String remoteHost;
  private int remotePort;
  
  private String protocol;
  
  public TransmitListener(int localPort, String remoteHost, int remotePort, String proxyHost, int proxyPort, String protocol)
  {
    this.localPort = localPort;
    
    this.remoteHost = remoteHost;
    this.remotePort = remotePort;
    
    this.proxyHost = proxyHost;
    this.proxyPort = proxyPort;
    
    this.protocol = protocol;
    
    super.setName("TransmitListener");
    super.setDaemon(false);
  }
  
  public void run()
  {
    try
    {
      this.privateRun();
    }
    catch (IOException e)
    {
      System.out.println("listener exit...");
    }
  }
  
  private void privateRun() throws IOException
  {
    Socket socket;
    
    try
    {
      System.out.println("listen on [" + this.localPort + "] using [" + this.protocol + "], remote[" + this.remoteHost + ":" + this.remotePort + "], proxy[" + this.proxyHost + ":" + this.proxyPort + "]...");
      this.serverSocket = new ServerSocket(this.localPort);
      this.serverSocket.setSoTimeout(0);  // 侦听永不超时。
    }
    catch (IOException e)
    {
      Log.global.error(e, "listener error.");
      this.serverSocket.close();
      return;
    }
    
    while (!Thread.interrupted())
    {
      try
      {
        socket = this.serverSocket.accept();
        
        Log.global.info("accept socket[", socket.getInetAddress().getHostAddress(), ":", socket.getPort(), "]");
        
        if (this.protocol.equalsIgnoreCase("HTTP"))
        {
          new HttpTransmitRelayConnector(socket, this.remoteHost, this.remotePort).connect();
        }
        else if (this.protocol.equalsIgnoreCase("SOCKET"))
        {
          new TransmitRelayConnector(socket, this.remoteHost, this.remotePort).connect();
        }
        else if (this.protocol.equalsIgnoreCase("AUTO_HTTP"))
        {
          new AutoHttpTransmitRelayConnector(socket, this.proxyHost, this.proxyPort, this.remoteHost, this.remotePort).connect();
        }
      }
      catch (IOException e)
      {
        Log.global.error(e, "listener error.");
      }
    }
  }

}
